import { reactive, getCurrentInstance, computed, inject } from 'vue'
import { useRouter } from 'vue-router'
import { UserApi } from '@@/api/api.js'

function useMessage() {
	const state = reactive({})
	const router = useRouter()
	const vueState = inject('vueState')
	const { props } = getCurrentInstance()
	const messageItem = computed(() => {
		return JSON.parse(props.item)
	})
	const messageList = computed(() => {
		return vueState.pageInfo.messageInfo.list
	})
	const showDetail = (item) => {
		window.trackEvent({ ev: 'clickMessagelist', remarks: `Title=${item.title}` })
		router.push({ name: 'messageDetail', params: { item: JSON.stringify(item) } })
	}
	const setReaded = (item) => {
		let unReadNum = 0
		try {
			vueState.pageInfo.messageInfo.list.forEach(el => {
				if (el.id === item.id && !el.readed) {
					// console.log('target','el',el,'item',item);
					el.readed = true
					UserApi.SetMessageReaded({ messageIds: [item.id] })
					// console.log('target-end','el',el,'item',item,'vueState',vueState.pageInfo);
				} else if (!el.readed) {
					unReadNum++
				}
			});
			window.SDKPostMessage({
				event: 'h5_letter_info',
				data: {
					'cnt_unread': unReadNum || 0
				}
			})
		} catch (e) {
			// console.log(e);
		}
	}
	const filtersText = (val) => {
		let reg = /<\/?.+?\/?>/g;
		let text = val.replace(reg, "");
		return text.replace(/&nbsp;/ig, ' ');
	}
	const formatTime = (time) => {
		const date = new Date(time)
		return `${date.getFullYear()}/${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}/${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()} ${date.getHours() < 10 ? '0' + date.getHours() : date.getHours()}:${date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()}`
	}
	return {
		showDetail,
		messageItem,
		setReaded,
		messageList,
		formatTime,
		filtersText
	}
}
export { useMessage }